//
//  ChangeLocalPhotoVC.swift
//  添加图片
//
//  Created by 雄 on 15/7/24.
//  Copyright © 2015年 雄. All rights reserved.
//

import UIKit

let LocalPhotoCellIdentifer = "LocalPhotoCellIdentifer_cell"

class ChangeLocalPhotoVC: UIViewController, UICollectionViewDataSource, ChangeLocalPhotoCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    // MARK: - 代理方法
    func cellSelectedImage() {
        // UIImagePickerController 专门用来选择照片的
        /**
        PhotoLibrary        照片库(所有的照片，拍照&用 iTunes & iPhoto `同步`的照片 - 不能删除)
        SavedPhotosAlbum    相册(自己拍摄的，可以随意删除)
        Camera              相机
        */
        let picker = UIImagePickerController()
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        
        // 设置代理
        picker.delegate = self
        
        // 允许编辑 － 如果要上传头像，记得把这个属性打开
        // 能够建立一个正方形的图像，方便后续的头像处理
        //        picker.allowsEditing = true
        
        // 转场
        presentViewController(picker, animated: true, completion: nil)

    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 添加图片 图形渲染,缩放图片
        images.append(image.scaleToWidth(300))
        collectionView.reloadData()
        
        // dismiss 
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    // 删除图片
    func cellRemoveImage(cell: ChangeLocalPhotoCell) {
        let indexPath = collectionView.indexPathForCell(cell)
        images.removeAtIndex(indexPath!.item)
        collectionView.reloadData()
    }
    
    // MARK: - UI
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.lightGrayColor()
        view.addSubview(collectionView)
        collectionView.registerClass(ChangeLocalPhotoCell.self, forCellWithReuseIdentifier: LocalPhotoCellIdentifer)
        
        picLayout.itemSize = CGSizeMake(80, 80)
        picLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        // 约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView": collectionView]))
         view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subView": collectionView]))
        
    }
    
    // MARK: - 懒加载
    lazy var picLayout = UICollectionViewFlowLayout()
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.picLayout)
    // 图片模型数组
    lazy var images = [UIImage]()
    
    // MARK: - dataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         // 末尾显示加号按钮，以便添加照片
        return images.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LocalPhotoCellIdentifer, forIndexPath: indexPath) as! ChangeLocalPhotoCell
        
        // 设置图像
        // photos.count 是数组最后一项 + 1
        cell.image = (indexPath.item == images.count) ? nil : images[indexPath.item]
        cell.photoCellDelegate = self
        
        return cell
    }
    
}

@objc
protocol ChangeLocalPhotoCellDelegate: NSObjectProtocol {
    optional func cellSelectedImage()
    optional func cellRemoveImage(cell: ChangeLocalPhotoCell)
}

class ChangeLocalPhotoCell: UICollectionViewCell {
    
    weak var photoCellDelegate: ChangeLocalPhotoCellDelegate?
    
    // 点击图片按钮
    func selectedImage() {
        if image == nil {
            photoCellDelegate?.cellSelectedImage!()
        }
    }
    // 点击关闭按钮
    func removeImage() {
        if image != nil {
            photoCellDelegate?.cellRemoveImage!(self)
        }
    }
    
    // 模型图片
    var image =  UIImage?() {
        didSet {
            if image != nil {
                imageBtn.setImage(image, forState: UIControlState.Normal)
                imageBtn.setImage(nil, forState: UIControlState.Highlighted)
                closeBtn.hidden = false
            } else {
                imageBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                imageBtn.setImage(UIImage(named: "ad_closebutton_background"), forState: UIControlState.Highlighted)
                closeBtn.hidden = true
            }
            
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(imageBtn)
        addSubview(closeBtn)
        closeBtn.hidden = true
        imageBtn.addTarget(self, action: "selectedImage", forControlEvents: UIControlEvents.TouchUpInside)
        closeBtn.addTarget(self, action: "removeImage", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 约束
        imageBtn.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: imageBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: imageBtn, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0))
        
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: closeBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: -3))
        addConstraint(NSLayoutConstraint(item: closeBtn, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 3))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载控件
     lazy var imageBtn: UIButton = self.createBtn("compose_pic_add")
     lazy var closeBtn: UIButton = self.createBtn("ad_closebutton_background")
    
     func createBtn(imgName: String) -> UIButton{
        let btn = UIButton()
        btn.setImage(UIImage(named: imgName), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: imgName + "_highlighted"), forState: UIControlState.Highlighted)
        
        return btn
    }
    
}

